package edu.ynu.se.xiecheng.achitectureclass.common.service;
import edu.ynu.se.xiecheng.achitectureclass.common.entity.*;
import edu.ynu.se.xiecheng.achitectureclass.common.repository.*;
import org.json.*;
import org.springframework.security.core.Authentication;  // 确保导入了 Spring Security 的 Authentication 类
import edu.ynu.se.xiecheng.achitectureclass.common.config.SecurityConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;

import java.time.LocalDateTime;
import java.util.*;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class SensorService {

    @Autowired
    private SensorRepository sensorRepository;

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CarbondioxideRepository carbondioxideRepository;
    @Autowired
    private SoilPHRepository soilphrepository;
    @Autowired
    private LightRepository lightrepository;
    @Autowired
    private TemperatureRepository temperatureRepository;
    @Autowired
    private HumidityRepository humidityRepository;


    private static final String API_URL = "https://fbox360.com/api/v2/dmon/value/get?boxNo={boxNo}";

    public String fetchAndSaveSensorData(String boxNo) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String u_id = "123456";  // 模拟获取当前登录用户的u_id，通常是通过authentication.getName()获取

        // 获取 access token
        User user = userRepository.findByUId(u_id);
        String accessToken = user.getAccessToken();

        // Step 1: 从数据库获取传感器 ID 列表
        List<Sensor> sensors = sensorRepository.findAll();
        List<String> sensorIds = new ArrayList<>();
        for (Sensor sensor : sensors) {
            sensorIds.add(sensor.getSensorId());
        }

        // Step 2: 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("ids", new JSONArray(sensorIds));
        // 打印请求体和请求头
        System.out.println("Request URL: " + API_URL);
        System.out.println("Request Body: " + requestBody.toString());

        // Step 3: 调用接口获取传感器数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + accessToken);
        // 打印请求头
        System.out.println("Request Headers: " + headers);


        HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.POST, entity, String.class, boxNo);

        if (response.getStatusCode() == HttpStatus.OK) {
            // Step 4: 解析返回的数据并存入数据库
            String responseBody = response.getBody();
            System.out.println("Raw Response Body: " + responseBody);  // 打印原始响应体
            if (responseBody == null || responseBody.isEmpty()) {
                return "No data received from the API";
            }

            System.out.println("Response Body: " + response.getBody());

            // 检查是否是一个 JSON 数组
            try {
                JSONArray responseArray = new JSONArray(responseBody);

                StringBuilder fetchedData = new StringBuilder();
                List<Map<String, Object>> allSensorData = new ArrayList<>();  // 用于存储每个传感器的数据
                for (int i = 0; i < responseArray.length(); i++) {
                    // 检查每个元素是否是 JSONObject
                    if (responseArray.get(i) instanceof JSONObject) {
                        JSONObject sensorData = responseArray.getJSONObject(i);

                        // 获取传感器字段
                        String sensorId = sensorData.getString("id");
                        String timestamp = sensorData.getString("timestamp");
                        String name = sensorData.getString("name");
                        double value = sensorData.getDouble("value");
                        String boxId = sensorData.getString("boxId");
                        int status = sensorData.getInt("status");
                        int connState = sensorData.getInt("connState");
                        String connStateTimestamp = sensorData.getString("connStateTimestamp");

                        // 特殊处理：空气温度和相对湿度需要除以10
                        if ("空气温度".equals(name) || "空气相对湿度".equals(name)) {
                            value = value / 10.0;  // 除以10得到实际值
                        }

                        // 如果传感器名称为 "carbondioxide"，将其存入 carbondioxide 表
                        if ("二氧化碳".equalsIgnoreCase(name)) {
                            // 保存到 carbondioxide 表
                            CarbonDioxide carbondioxide = new CarbonDioxide();
                            carbondioxide.setSensorName(name);
                            carbondioxide.setSensorId(sensorId);
                            carbondioxide.setSensorPrice(value);
                            carbondioxide.setUpdateTime(LocalDateTime.now());

                            // 保存到数据库
                            carbondioxideRepository.save(carbondioxide);
                        }
                        // 如果传感器名称为 "soilPH"，将其存入 soilPH 表
                        if ("土壤PH值".equalsIgnoreCase(name)) {
                            // 保存到 soilPH 表
                            SoilPH soilph = new SoilPH();
                            soilph.setSensorName(name);
                            soilph.setSensorId(sensorId);
                            soilph.setSensorPrice(value);
                            soilph.setUpdateTime(LocalDateTime.now());

                            // 保存到数据库
                            soilphrepository.save(soilph);
                        }
                        // 如果传感器名称为 "Light"，将其存入 Light 表
                        if ("光照度".equalsIgnoreCase(name)) {
                            // 保存到 light 表
                            Light light = new Light();
                            light.setSensorName(name);
                            light.setSensorId(sensorId);
                            light.setSensorPrice(value);
                            light.setUpdateTime(LocalDateTime.now());

                            // 保存到数据库
                            lightrepository.save(light);
                        }
                        // 如果传感器名称为 "Temperature"，将其存入 Temperature 表
                        if ("空气温度".equalsIgnoreCase(name)) {
                            // 保存到 temperature 表
                            Temperature temperature = new Temperature();
                            temperature.setSensorName(name);
                            temperature.setSensorId(sensorId);
                            temperature.setSensorPrice(value);
                            temperature.setUpdateTime(LocalDateTime.now());

                            // 保存到数据库
                            temperatureRepository.save(temperature);
                        }
                        // 如果传感器名称为 "Humidity"，将其存入 Humidity 表
                        if ("空气相对湿度".equalsIgnoreCase(name)) {
                            // 保存到 Humidity 表
                            Humidity humidity = new Humidity();
                            humidity.setSensorName(name);
                            humidity.setSensorId(sensorId);
                            humidity.setSensorPrice(value);
                            humidity.setUpdateTime(LocalDateTime.now());

                            // 保存到数据库
                            humidityRepository.save(humidity);
                        }

                        // 拼接返回的数据字符串
                        fetchedData.append("Sensor ID: ").append(sensorId)
                                .append(", Name: ").append(name)
                                .append(", Value: ").append(value)
                                .append(", Timestamp: ").append(timestamp)
                                .append("\n");

                        // 将数据存储在 allSensorData 列表中
                        Map<String, Object> sensorRecord = new HashMap<>();
                        sensorRecord.put("sensorId", sensorId);
                        sensorRecord.put("name", name);
                        sensorRecord.put("value", value);
                        sensorRecord.put("timestamp", timestamp);
                        sensorRecord.put("boxId", boxId);
                        sensorRecord.put("status", status);
                        sensorRecord.put("connState", connState);
                        sensorRecord.put("connStateTimestamp", connStateTimestamp);

                        allSensorData.add(sensorRecord);
                    } else {
                        // 如果响应中的某个元素不是 JSONObject，记录并继续
                        System.out.println("Non-JSONObject element found at index " + i);
                    }
                }

                // 将所有传感器的数据作为 JSON 返回给前端
                JSONObject result = new JSONObject();
                result.put("fetchedData", fetchedData.toString());
                result.put("sensorData", allSensorData);


                // 返回获取的传感器数据
                return fetchedData.toString();
            } catch (JSONException e) {
                // 捕获 JSON 解析错误
                System.out.println("Error parsing JSON response: " + e.getMessage());
                return "Error parsing JSON response: " + e.getMessage();
            }
        } else {
            // 请求失败时的处理
            System.out.println("Error calling API: " + response.getStatusCode());
            return "Error calling API: " + response.getStatusCode();
        }
    }


    public Map<String, List<?>> getSensorData(String sensorType) {
        Map<String, List<?>> sensorData = new HashMap<>();

        switch (sensorType.toLowerCase()) {
            case "carbondioxide":
                List<CarbonDioxide> carbondioxideData = carbondioxideRepository.findAll();
                sensorData.put("carbonDioxide", carbondioxideData);
                break;
            case "soilph":
                List<SoilPH> soilPHData = soilphrepository.findAll();
                sensorData.put("soilPH", soilPHData);
                break;
            case "light":
                List<Light> lightData = lightrepository.findAll();
                sensorData.put("light", lightData);
                break;
            case "temperature":
                List<Temperature> temperatureData = temperatureRepository.findAll();
                sensorData.put("temperature", temperatureData);
                break;
            case "humidity":
                List<Humidity> humidityData = humidityRepository.findAll();
                sensorData.put("humidity", humidityData);
                break;
            default:
                throw new IllegalArgumentException("Unknown sensor type: " + sensorType);
        }

        return sensorData;
    }
}
